define([
	'jquery',
	'iCheck',
	'xss',
	'layer',
	'jquery_ui',
	'scrollbar',
	'checkAll',
	'imgCenter',
	'zPage'
], function($, iCheck, xss, layer) {

	return {
		//接口请求传值
		to_data: {
			id: pageId,
			shopId: shopId,
			page: page
		},
		//初始化
		init: function() {
			$("#boxscroll").niceScroll({
				cursorborder: "",
				cursorcolor: "#d0d0d0",
				boxzoom: false
			}); // First scrollable DIV

			var _this = this;
			_this.getData(_this.to_data, function(data) {
				_this.processData(data);
			});
			_this.pageNameCut();
			_this.saveClick();
		},

		//处理链接
		batchLink: function(obj) {
			var newObj = {};
			for(k in obj) {
				newObj[k] = [];
				for(var i = 0; i < obj[k].length; i++) {
					if(obj[k][i].child) {
						var clen = obj[k][i].child.length;
						if(clen > 0) {
							obj[k][i]["disabled"] = true;
							newObj[k].push(obj[k][i]);
							for(var o = 0; o < clen; o++) {
								newObj[k].push(obj[k][i].child[o]);
							}
						} else {
							newObj[k].push(obj[k][i]);
						}
					} else {
						newObj[k].push(obj[k][i]);
					}
				}
			}
			return newObj;
		},

		//链接
		allLink: link_list,
		//商品数量 
		//微页名称
		pageName: "",
		//模块总数量
		maxMoudleNum: undefined,

		//手机上下箭头点击事件(用滚动条代替)
		moblieScroll: function() {
			var nowscroll = $('.hb_box').height();
			$(".phone_bg i.up").unbind("click").click(function() {
				$('.hb_box').animate({
					scrollTop: '-=' + nowscroll
				}, 'fast');
			});
			$(".phone_bg i.down").unbind("click").click(function() {
				$('.hb_box').animate({
					scrollTop: '+=' + nowscroll
				}, 'fast');
			});
			$(".phone_bg i.home").unbind("click").click(function() {
				$('.hb_box').animate({
					scrollTop: '0'
				}, 'fast');
			});
		},

		//iCheck参数
		iCheckOption: {
			checkboxClass: 'icheckbox_minimal-yellow',
			radioClass: 'iradio_square-yellow',
			increaseArea: '20%'
		},

		//微页名称裁剪
		pageNameCut: function() {
			var _this = this;
			$("input[name='pageName']").on("blur keydown", function() {
				var thisval = $(this).val();
				thisval = filterXSS(_this.html_encode(thisval));
				_this.pageName = thisval;
				if(thisval.lenght > 20) {
					thisval = thisval.slice(0, 20);
					$(this).val(thisval);
				}
				if((thisval != "" || thisval != null) && $(this).next("span[class='help-inline']").length > 0) {
					$(this).next("span").remove();
					$(this).removeClass("error");
				}
			});
		},

		//微页名称验证
		pageNameCheck: function() {
			var _this = this,
				$pageName = $("input[name='pageName']"),
				thisval = _this.pageName;
			var pname = $pageName.val();
			this.pageName = $pageName.val()
			if(pname == "" || pname == null) {
				$pageName.addClass("error");
				if($pageName.next("span[class='help-inline']").length <= 0) $pageName.after("<span for='name' class='help-inline'>微页名称不能为空。</span>");
				$('.wrap_body_inner').animate({
					scrollTop: 0
				}, 'fast');
				return false;
			} else {
				return true;
			}
		},
		//保存验证提交,
		saveClick: function() {
			var _this = this;
			$("#saveFormbtn").unbind("click").click(function() {
				if(!(_this.pageNameCheck())) return; //微页名称验证

				_this.saveSubmit();
			});
		},
		saveSubmit: function() {

			var _this = this;

			function deleteTishi(key) {
				if($(".edit-inner[key='" + key + "'] .edit-panel-con").find("div").first().hasClass("tips_box")) {
					$(".edit-inner[key='" + key + "'] .edit-panel-con").find("div").first().remove();
				}
			}

			function tishi(_that, key, content) {
				deleteTishi(key);
				$(".edit-inner[key='" + key + "'] .edit-panel-con").prepend("<div class='tips_box bgee'>" +
					"<span class='red'>*</span><strong>注意：</strong>" + content +
					"</div>");
				$(".edit-inner").hide();
				$(".edit-inner[key='" + key + "']").show();
				$(".hb_box .panel-comp").removeClass("active");
				$(_that).addClass("active");

				var thatTop = $(_that).offset().top,
					panelsTop = $('.hb_box .panel-comp:eq(0)').offset().top;

				newTop = (thatTop - panelsTop);
				$(".edit-panel_outer,.phone").niceScroll({
					cursorborder: "",
					cursorcolor: "#d0d0d0",
					boxzoom: false
				});
				// First scrollable DIV
				layer.msg(content, {
					time: 2000
				});

			}

			function isNullObj(obj) {
				for(var i in obj) {
					if(obj.hasOwnProperty(i)) {
						return false;
					}
				}
				return true;
			}

			if(isNullObj(g_data)) {
				layer.msg("微页面中一个组件都没有!不能保存哦。", {
					time: 2000
				});
				return;
			}
			var comptypes = [];
			var submitTrue = false;
			$(".hb_box .panel-comp").each(function() {

				var key = $(this).attr("key"),
					comptype = $(this).attr("compType"),
					order = parseInt($(".hb_box .panel-comp").index(this));
				comptypes.push(comptype);

				g_data[key].order = order;

				//验证环节
				switch(comptype) {

					//公告模块                            
					case "notice":
						if(g_data[key].prop.noticeValue.length < 1 || g_data[key].prop.noticeValue == "" || g_data[key].prop.noticeValue == null) {
							var content = "公告内容不能为空哦。";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//商品模块                            
					case "goods":
						if(g_data[key].ItemList.length < 1) {
							var content = "至少选择一个商品";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//活动模块                            
					case "serviceItem":
						if(g_data[key].ItemList.length < 1) {
							var content = "至少选择一个活动";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;
						//客服电话                            
					case "tell":
						if(g_data[key].prop.tellNum == "" || g_data[key].prop.tellNum == null) {
							var content = "客服电话不能为空";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//标题                            
					case "title":
						if(g_data[key].prop.titleVal == "" || g_data[key].prop.titleVal == null) {
							var content = "标题不能为空";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else if(g_data[key].prop.isimg == '1' && (g_data[key].prop.logoId == "" || g_data[key].prop.logoUrl == "")) {
							var content = "标题左侧图标必须上传";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else if(g_data[key].prop.rightVal != "" &&
							(g_data[key].prop.righturlname == "" ||
								g_data[key].prop.righturl == "" ||
								g_data[key].prop.all_link == "" ||
								$(".edit-inner[key='" + key + "']").find(".STH_title_select2").val() == '')) {
							var content = "右侧文字“" + g_data[key].prop.rightVal + "”必须选择链接";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//文本富媒体                            
					case "text":
						if(g_data[key].ItemList[0].html == "" || g_data[key].ItemList[0].html == null) {
							var content = "文本内容不能为空";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//视频                            
					case "vedio":
						if(g_data[key].prop.vediosrc == "") {
							var content = "视频不能为空";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//导航                            
					case "navs":
						if(typeof(g_data[key].ItemList) == "undefined" || g_data[key].ItemList.length < 1) {
							var content = "导航不能为空";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else if($(".edit-inner[key='" + key + "']").find(".STH_navs_edit .level2 select").val() == '') {
							var content = "导航链接必须选择";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							for(var i = 0; i < g_data[key].ItemList.length; i++) {
								if(g_data[key].ItemList[i].navText == "") {
									var content = "导航第" + (i + 1) + "个文字不能为空";
									tishi(this, key, content);
									submitTrue = false;
									return false;
								}
								if(g_data[key].ItemList[i].navUrl == "") {
									var content = "导航第" + (i + 1) + "个链接必须选择";
									tishi(this, key, content);
									submitTrue = false;
									return false;
								}
							}
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//幻灯片                            
					case "swiper":
						if(g_data[key].ItemList.length < 1) {
							var content = "幻灯片至少要有一张图片";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							for(var i = 0; i < g_data[key].ItemList.length; i++) {
								if(g_data[key].ItemList[i].imgid == "" || g_data[key].ItemList[i].src == "") {
									var content = "第" + (i + 1) + "张必须上传图片";
									tishi(this, key, content);
									submitTrue = false;
									return false;
								}

							}
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//图片                            
					case "images":
						if(g_data[key].ItemList.length < 1) {
							var content = "至少要有一张图片";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							for(var i = 0; i < g_data[key].ItemList.length; i++) {
								if(g_data[key].ItemList[i].Fsrc == "") {
									var content = "第" + (i + 1) + "张必须上传图片";
									tishi(this, key, content);
									submitTrue = false;
									return false;
								}

							}
							deleteTishi(key);
							submitTrue = true;
						}
						break;

						//优惠券                            
					case "coupon":
						if(g_data[key].ItemList.length < 1) {
							var content = "至少要有一种优惠券";
							tishi(this, key, content);
							submitTrue = false;
							return false;
						} else {
							deleteTishi(key);
							submitTrue = true;
						}
						break;
				}
			});
			if(submitTrue) {
				$.each(g_data, function(i, gdata) {
					var isexc = false;
					$.each(comptypes, function(c, com) {
						if(com == gdata.type) {
							isexc = true;
						}
					})
					if(!isexc) {
						delete g_data[i];
					}
				});
			}

			//提交微页面
			if(submitTrue) {
				var savelayer = layer.load(1);
				var s_data = {};
				var url = BaseUrl + "Page?token=" + $api.getStorage("token");
				var area = 0;

				if(!$api.isEmpty(_this.to_data.id)) {
					url += "&action=edit";
				} else {
					url += "&action=add";
				}
				var rows = [];
				for(var i in g_data) {
					g_data[i].prop = JSON.stringify(g_data[i].prop);
					rows.push(g_data[i]);
				} 

				var param = {
					List: rows,
					PageName: _this.pageName,
					ID: _this.to_data.id
				};
 

				$.ajax({
					type: 'post',
					url: url,
					data: param,
					async: true,
					dataType: 'json',
					success: function(obj) {
						layer.close(savelayer);
						if(obj.Code == 100) {
							u.clearStorage();
							layer.msg(obj.Message, {
								icon: 1,
								time: 2000
							}, function() {
								window.location.href = "../../index.html";
							});
						} else if(obj.Code == 0) {
							layer.msg('保存成功！', {
								icon: 1,
								time: 2000
							}, function() {
								location.href = "List.html?mid=" + mid; //此处要跳转到列表页
							});
						} else {
							for(var i in g_data) {
								g_data[i].prop = JSON.parse(g_data[i].prop);

							}
							layer.msg('保存失败！', {
								icon: 1,
								time: 4000
							});
						}

					},
					error: function(data) { 
						layer.msg('系统繁忙，请重试！！', {
							icon: 1,
							time: 2000
						});
					}
				});

			}
		},

		//根据模板ID拉取数据库中的g_data
		getData: function(to_data, callback) {
			var _this = this;
			//初始化模块
			if(to_data.id != "0") {
				var url = BaseUrl + "Page?token=" + $api.getStorage("token") + "&Fpageid=" + to_data.id;
				$.ajax({
					type: 'get',
					url: url,
					data: {},
					async: true,
					dataType: 'json',
					success: function(res) {
						console.log(res);
						if(res.Code == 100) {
							u.clearStorage();
							layer.msg(res.Message, {
								icon: 1,
								time: 2000
							}, function() {
								window.location.href = "../../index.html";
							});
						} else if(res.Code == 0) {
							$("input[name='pageName']").val(res.PageName);
							_this.pageName = res.PageName;
							if(res.Rows) {
								var data = res.Rows
								if($.type(callback) == "function") {
									callback(data);
								} else {
									_this.dragEdit();
								}
							} else {
								_this.dragEdit();
							}
						} else {
							_this.dragEdit();
						}

					},
					error: function(data) { 
						layer.msg('系统繁忙，请重试！！', {
							icon: 1,
							time: 2000
						});
					}
				});

			} else {
				// 是新建空模板,判断营销活动存在，默认加入
				if($(".tab-pane ul li.market").length >= 1) {
					var key = 0,
						order = 0,
						comptype = "market",
						newPanel = _this.getPanel(comptype),
						newEdit = _this.getEdit(comptype);

					$(newPanel).attr("key", key);
					$(newEdit).attr("key", key);

					$(".hb_box").prepend(newPanel);
					$(".edit-panel").append(newEdit);
					if($(".hb_box .panel-comp").length > 0) {
						$(".Kongtishi").fadeOut();
					}
					_this.addG_data(comptype, key, order);
					_this.requreType(key, comptype);
				}
				_this.dragEdit();
			}
		},

		//处理拉取的g_data
		processData: function(data) {
			var _this = this;
			$.extend(g_data, data);
			var tempCon = [],
				tempKey = [];
			for(key in g_data) {
				//if(typeof g_data[key]['key'] == "undefined") g_data[key]['key'] = key;
				tempKey.push(key);
				console.log(g_data[key]);
				if(!$api.isEmpty(g_data[key].prop))
					g_data[key].prop = JSON.parse(g_data[key].prop);
				g_data[key].key = key;
				console.log(g_data[key].prop);
				tempCon.push(g_data[key]);
			}

			_this.shellSort(tempCon);
			g_key = Math.max.apply(null, tempKey); //得出最新的key

			var conLength = tempCon.length;

			for(var i = 0; i < conLength; i++) {
				console.log(tempCon[i]);
				_this.addMoudle(tempCon[i].type, tempCon[i]);
			}
		},

		//根据comptype不同向显示中新增模块
		addMoudle: function(comptype, con) {
			require(['../../js/JScripts/Shop/module/STH_' + comptype + '.js'], function(module) {
				var nameAddM = comptype + "AddM";
				module[nameAddM](con);
			});
		},

		//新增模块时编辑全局g_data
		addG_data: function(comptype, key, order) {
			var _this = this;
			g_data[key] = {
				"key": key,
				"type": comptype,
				"prop": {},
				"ItemList": [],
				"order": order
			};
		},

		//整体模块切换及删除操作
		moduleActive: function() {
			var _this = this;
			if($(".hb_box .panel-comp").length > 0) {
				$(".Kongtishi").fadeOut();
			}

			//切换
			$(".hb_box .panel-comp").unbind("click").click(function() {
				var index = $(".hb_box .panel-comp").index(this),
					key = $(this).attr("key");
				$(".hb_box .panel-comp").removeClass("active").eq(index).addClass("active");
				$('.edit-inner').hide();
				$(".edit-inner[key='" + key + "']").show();
			});

			//删除
			$(".hb_box .panel-comp .actions").unbind("click").click(function(e) {
				e.stopPropagation();
				var key = $(this).parents(".panel-comp").attr("key");
				layer.confirm("确定需要删除这个模块吗？", { 
					icon: 3,
					title: '提示'
				}, function(index) {
					layer.close(index);
					delete g_data[key];
					$(".panel-comp[key='" + key + "']").remove();
					$(".edit-inner[key='" + key + "']").remove();
					if($(".hb_box .panel-comp").length < 1) {
						$(".Kongtishi").fadeIn();
					}
				});
			});
		},

		//拖动
		dragEdit: function() {
			var _this = this;
			$comp_list = $('.tab-pane ul li');
			$panel_comps = $('.hb_box');
			$design_edit = $('.edit-panel');

			var comptype = "",
				maxCnum = "",
				mName = "";

			$comp_list.draggable({
				connectToSortable: $panel_comps,
				revert: "invalid",
				helper: "clone",
				cursor: "move",
				start: function() {
					comptype = $(this).attr('compType');
					maxCnum = $(this).attr('maxNumber');
					mName = $(this).find("span.text").html();
				}
			}).disableSelection();

			$panel_comps.droppable({
				accept: '.tab-pane ul li',
				activate: function(event, ui) {
					ui.draggable.attr("noro", "new");
				}
			});

			$panel_comps.sortable({
				axis: 'y',
				placeholder: 'ui-state-placeholder',
				items: ".panel-comp",
				opacity: .6,
				start: function(event, ui) {
					ui.placeholder.height(ui.item.height() - 2);
					comptype = ui.item.attr('compType');
				},
				stop: function(event, ui) {

					var noro = ui.item.attr("noro");
					//如果是拖进新增
					if(noro == "new") {
						var nowMnum = 0,
							nowCMnum = 0;
						for(d in g_data) {
							nowMnum++;
							if(g_data[d].type == comptype) {
								nowCMnum++;
							}
						}

						if(_this.maxMoudleNum != undefined && nowMnum >= maxMoudleNum) {
							layer.msg("页面组件数量超过最大值：" + _this.maxMoudleNum + "个，不能再添加了", {
								time: 3000
							});
							ui.item.remove();
							return;
						}

//						if(maxCnum != "" && nowCMnum >= parseInt(maxCnum)) {
//							layer.msg(mName + "组件同一页面中只能有" + maxCnum + "个哦", {
//								time: 3000
//							});
//							ui.item.remove();
//							return;
//						}

						var newPanel = _this.getPanel(comptype);
						if((typeof(comptype) != "undefined") && newPanel) {
							var newEdit = _this.getEdit(comptype),
								key = g_key + 1;

							$(newPanel).attr("key", key);
							$(newEdit).attr("key", key);
							ui.item.after(newPanel);
							if($(".hb_box .panel-comp").length > 0) {
								$(".Kongtishi").fadeOut();
							}
							$design_edit.prepend(newEdit);
							var order = $panel_comps.find(".panel-comp").index($panel_comps.find(".panel-comp[key='" + key + "']"));
							order = order + 1;
							_this.addG_data(comptype, key, order);
							g_key = key;
							_this.requreType(key, comptype);
						} else {
							layer.msg("此项组件还未开发！", {
								time: 2000
							});
						}
						ui.item.remove();
					} else {}
				}
			}).disableSelection();
		},

		//获取组件在手机显示处HTML
		getPanel: function(compType) {
			var panel = $('#tp-panel').html(),
				domHtml = "",
				totalDom = $(panel),
				len = totalDom.length;
			for(var i = 0; i < len; i++) {
				var the_compType = $(totalDom[i]).attr('compType');
				if(the_compType == compType) {
					domHtml = totalDom[i]
					break;
				}
			}
			return domHtml;
		},
		showLinkDialog: function(callback) {

		},
		//获取组件操作处的HTML
		getEdit: function(compType) {
			var edit = $('#tp-edit').html(),
				domHtml = "",
				totalDom = $(edit),
				len = totalDom.length;
			for(var i = 0; i < len; i++) {
				var the_compType = $(totalDom[i]).attr('compType');
				if(the_compType == compType) {
					domHtml = totalDom[i]
					break;
				}
			}
			return domHtml;
		},

		//参数调动效果，根据comptype和key键
		requreType: function(key, comptype) {
			var _this = this,
				$thisPanel = $(".hb_box .panel-comp[key='" + key + "']"),
				$thisEdit = $(".edit-panel .edit-inner[key='" + key + "']");
			$(".hb_box .panel-comp").removeClass("active");
			$thisPanel.addClass("active");
			$(".edit-panel .edit-inner").hide();
			$thisEdit.show();
			require(['../../js/JScripts/Shop/module/STH_' + comptype + '.js?version=20180511'], function(module) {
				var nameActive = comptype + "Active";
				module[nameActive]($thisPanel, $thisEdit, key);
			});

		},

		//图片dialog
		photoDialog: function(callback) {
			parent.showPhotoDialog2(callback);
		},
		//活动dialog
		activityDialog: function(callback) {
			parent.showPhotoDialog2(callback);
		},
		//商品dialog
		productDialog: function(param, callback) {
			parent.f_ProductWin2(param, callback);
		},
		//分类dialog
		typeDialog: function(callback) {
			parent.showPTypeDialog(callback);
		},
		commonDialog: function(url, title, width, height, callback) {
			parent.openCommWindow2(url, title, width, height, callback);
		},
		commonDialog3: function(url, title, width, height, callback) {
			parent.openCommWindow3(url, title, width, height, callback);
		},
		//模板填充
		formatTemplate: function(data, tmpl) {
			return tmpl.replace(/{(\w+)}/g, function(m1, m2) {
				if(!m2)
					return "";
				return data[m2];
			});
		},

		//按顺序号排序
		shellSort: function(arr) {
			for(var step = arr.length >> 1; step > 0; step >>= 1) {
				for(var i = 0; i < step; ++i) {
					for(var j = i + step; j < arr.length; j += step) {
						var k = j,
							value = arr[j].order,
							tmp = arr[j];
						while(k >= step && arr[k - step].order > value) {
							arr[k] = arr[k - step];
							k -= step;
						}
						arr[k] = tmp;
					}
				}
			}
			return arr;
		},

		//数组移换位置
		exchange: function(arr, index1, index2) {
			arr[index1] = arr.splice(index2, 1, arr[index1])[0];
			return arr;
		},

		//数组置顶（换到最前）
		toTop: function(arr, index) {
			var newVal = arr[index];
			arr.unshift(newVal);
			arr.splice(index + 1, 1);
			return arr;
		},

		//数组置底（换到最后）
		toBottom: function(arr, index) {
			var newVal = arr[index];
			arr.push(newVal);
			arr.splice(index, 1);
			return arr;
		},

		//解转义
		html_decode: function(str) {
			var s = "";
			if(str.length == 0) return "";
			s = str.replace(/&gt;/g, ">");
			s = s.replace(/&lt;/g, "<");
			s = s.replace(/&nbsp;/g, " ");
			s = s.replace(/&#39;/g, "\'");
			s = s.replace(/&quot;/g, "\"");
			s = s.replace(/\\n/g, "<br>");
			return s;
		},

		//转义
		html_encode: function(str) {
			var s = "";
			if(str.length == 0) return "";
			s = str.replace(/>/g, "&gt;");
			s = s.replace(/</g, "&lt;");
			//		    s = s.replace(/ /g, "&nbsp;");
			//		    s = s.replace(/'/g, "&#39;");
			//		    s = s.replace(/"/g, "&quot;");
			//		    s = s.replace(/<br>/g, "\n");
			return s;
		}

	}
});